import cgi

from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db

import urllib
from google.appengine.api import urlfetch

import sys
import httplib
import re
import string

import datastore
import library
from datetime import date

class USTAYear(db.Model):

 def GetRecord(self,year,league, start,finish):

    query="select __key__ from USTATeam where league='M4.0' limit 3"
    print query
    keys =  db.GqlQuery( query )

    year = "2011"
    league = "Adult League Mens 4.0" 
    for k  in keys:
        t = db.get(k)
        print t.teamid,t.name
        thePlayers= library.getTeamPlayers(t.teamid)
        for p in thePlayers:
          record = library.getWinLossRecord(year,league,p[0])
          win=0
          loss=0
          for r in record:
              win  += int(r[4])
              loss += int(r[5])
          print  p[1], p[2],win,loss


 def GetWinLossRecord(self,start,finish):
    def Add(data):
      return ',"' + data + '"'

    # M3.5 listed in order of record

    playerid="118652"  # Rose
    playerid="111468"  # JJung
    playerid="38270"   # Lynne Lucas
    playerid="114892"  # Cai
    playerid="42194"   # Noram Sanchez-Hoxie
    playerid="11507"   # Greta 
    playerid="32778"   # Lori

#   Get League record
    year = "2011"
    division = "Adult League Womens 4.0"

    r = library.getWinLossRecord(year,division,playerid)

    win=loss=0
    for i,e in enumerate(r):
      print(e )
      win += int(e[4])      
      loss += int(e[5])      

    print("WIN = ",win, "LOSS= ",loss)
    g = datastore.USTASeasonRecord( key_name= playerid )
#   g.fname="Lori"
    g.win = "14" # str(win)
    g.loss = str(loss)
 
    print( "put " )
    db.put( g  )     #Put into db 


 def show(self):
    query="select __key__ from League order by idx"
    keys  = db.GqlQuery( query )
    for k in keys:
     t = db.get(k)
     print t
     print t.name


# ------------------------


class MainPage(webapp.RequestHandler):

  def Write(self,t):
    self.response.out.write(t)

  def get(self):

    league =  self.request.get('league') 
    start =  self.request.get('start') 
    finish =  self.request.get('finish') 
    if(start=="" or finish==""):  
       start=0
       finish=5

#  insert league selection

    year="2011"
    league = "Adult League Mens M4.0"
    u = USTAYear()
    u.GetRecord( year,league, int(start), int(finish)  )


application = webapp.WSGIApplication(
                                     [('/ustayear', MainPage)],
                                     debug=True)


def main():
    run_wsgi_app(application)

if __name__ == "__main__":

#   print __file__
#   print __name__

    main()
